# -*- coding:UTF-8 -*-
'''
Entry of main

Created on 2012-10-26

@author: DANG Zhengfa
'''
# load system modules
import webapp2
from webapp2 import RequestHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from webapp2 import uri_for, Route
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
# from webapp2_extras.routes import RedirectRoute
import logging
import urllib
import datetime
from webapp2_extras import i18n
# from webapp2_extras import i18n

# load modules defined by this app
from utilities import render_template
from BaseRequestHandler import BaseRequestHandler
from timeline import Timeline
from model import DBPhoto, Setting


class IndexHandler(BaseRequestHandler):
    '''
    classdocs
    '''
    def get(self, page="1", cate_slug=""):
        t_values = {}

        # load headline from setting
        title = None
        host = None
        settings = Setting.all()
        if settings.count() == 1:
            setting = settings[0]
            title = setting.headline
            host = setting.host
        t_values['title'] = title
        t_values['host'] = host

        # show index page
        return self.response.out.write(render_template("index.html", t_values, "basic", False))


class TimelineHandler(BaseRequestHandler):
    '''
    classdocs
    '''
    def get(self):
        tr = None

        settings = Setting.all()
        album_start_date = datetime.datetime.strptime("2012-09-18", "%Y-%m-%d")
        if settings.count() == 1:
            setting = settings[0]
            tr = Timeline(setting.headline, setting.text, setting.start_date.replace("-", ","))
            album_start_date = datetime.datetime.strptime(setting.start_date, "%Y-%m-%d")
        else:
            tr = Timeline("Photos in Timeline", "this is the text", '2011,9,18')

        # add photos into timeline
        photos = DBPhoto.all().filter("public =", True).order("-start_date")
        for photo in photos:
            photo_start_date = datetime.datetime.strptime(photo.start_date, "%Y-%m-%d")
            days_of_album = (photo_start_date - album_start_date).days + 1
            tr.add_date(photo.start_date.replace("-", ","), photo.headline, \
             photo.gen_thumb_url(), photo.end_date.replace("-", ","), \
             text=photo.text + "<BR/><BR/><A href='%s'><i class='icon-zoom-in'></i>%s</A>" % (photo.gen_html_url(), photo.photo_name), asset_caption=i18n.gettext("Day %d") % (days_of_album))

        self.response.charset = "UTF-8"
        self.response.content_type = "application/json"
        # logging.info("json = %s" % (tr.get_json()))
        self.response.write(tr.get_json())


class HTMLHandler(BaseRequestHandler):
    '''
    classdocs
    '''
    def get(self, filename):
        t_values = {}
        filename = unicode(urllib.unquote(filename), "UTF-8")
        photos = DBPhoto.all().filter("photo_name =", filename)
        if photos.count() == 0:
            logging.error("filename %s has zero entries!" % (filename))
            self.response.write("Inalid filename %s" % (filename))
            return
        if photos.count() > 1:
            logging.error("filename %s has multiple entries (%d)!" % (filename, photos.count()))
        # delivery photo
        photo = photos[0]
        t_values['photo_url'] = photo.gen_url()
        t_values['photo_thumb_url'] = photo.gen_thumb_url()
        t_values['photo_name'] = photo.photo_name

        # show index page
        self.response.content_type = "text/html"
        return self.response.out.write(render_template("photo.html", t_values, "basic", False))


class PhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
    '''
    classdocs
    '''
    def get(self, filename, thumb=""):
        filename = unicode(urllib.unquote(filename), "UTF-8")
        photos = DBPhoto.all().filter("photo_name =", filename)
        key = None
        if photos.count() == 0:
            logging.error("filename %s has zero entries!" % (filename))
            self.response.write("Inalid filename %s" % (filename))
            return
        if photos.count() > 1:
            logging.error("filename %s has multiple entries (%d)!" % (filename, photos.count()))

        # delivery photo
        photo = photos[0]
        if thumb == "thumb":
            key = photo.thumb_blob_key
        else:
            key = photo.blob_key
        blob_info = blobstore.BlobInfo.get(key)
        self.send_blob(blob_info)


class LocaleHandler(RequestHandler):
    '''
    classdocs
    '''
    def get(self):
        referer = self.request.referer
        locale = self.request.GET.get("value", "en_US")
        logging.info("LocaleHandler: %s set locale to %s" % (referer, locale))
        if locale:
            self.response.set_cookie("locale", locale)
        if referer:
            self.redirect(referer)
        else:
            self.redirect(uri_for("main.index"))


##########################################################
# define routers
routes = [
          Route('/', handler='main.IndexHandler', name="main.index"),
          Route('/locale', handler='main.LocaleHandler', name="main.locale"),
          Route('/timeline', handler='main.TimelineHandler', name="main.timeline"),
          Route('/photo/<thumb>/<filename>', handler='main.PhotoHandler', name="main.photo.thumb"),
          Route('/photo/<filename>', handler='main.PhotoHandler', name="main.photo"),
          Route('/html/<filename>', handler='main.HTMLHandler', name="main.html"),
          ]

application = webapp2.WSGIApplication(routes, debug=True)


# main goes here
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
